package fr.ece.ing4.si.montecarlo;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Random;

public class monteCarlo {
	
	private String callPutFlag;
	private double s ;
	private double x ;
	private double T ;
	private double r ;
	private double b ;
	private double v ;
	private int nSteps ;
	private int nSimulations ;
	private double st; 
	private double dt;
	private double drift; 
	private double vSqrdt;
	private double sum;
	private int z;
	private int i;
	private double result;

	//Constructor
	public monteCarlo(String callPutFlag, double s,	double x, double T, double r, double b,	
			double v, int nSteps, int nSimulations)
	{
		this.callPutFlag= callPutFlag;
		this.s=s;
		this.x=x;
		this.T=T;
		this.r=r;
		this.b=b;
		this.v=v;
		this.nSteps=nSteps;
		this.nSimulations=nSimulations;
	}
	
	//Method to load 6 parameters from the text files
	//s,x,T,r,b,v
	public static String[] readParameters() throws IOException {
		
		final BufferedReader reader = 
			      new BufferedReader(new FileReader("params.txt"));
	    String stockInfo = null;
	    String[] params = null;
		while((stockInfo = reader.readLine()) != null) {
	    	params = stockInfo.split(",");
	    }
	    reader.close();
	    return params;    
	  }

	//Method of the Montecarlo Algorithm to get the Premium
	public double computePremium()
		    throws IOException {
		
		//Set the primary values
				dt = this.T/ this.nSteps;
				drift = (this.b - (this.v*this.v) / 2) * dt; 
				vSqrdt = this.v * Math.sqrt(dt);
				z=0;
				if (this.callPutFlag =="c"){
					z=1; 
				}
				else if (this.callPutFlag =="p"){
					z=-1; 
				}
		
				Random rand = new Random(); 
				sum = 0;
				for (i=1; i<= nSimulations; i++){
					st = this.s; 
					for (int j=1; j<= nSteps; j++){
						st = st * Math.exp(drift + vSqrdt * rand.nextGaussian()); 
					}
					sum = sum + Math.max(z*(st-this.x), 0);
					//listner.update(((i/this.nSimulations)*100));
					//setProgress(((i/this.nSimulations)*100));
				}
				result = (Math.exp(-this.r*this.T)) * (sum/this.nSimulations) ; 
				return result;
		  } 
}
